<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>兄弟节点</title>
    <script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
    <style>
      .parent {
        width: 600px;
        min-height: 300px;
        background-color: pink;
        padding: 20px;
      }
      .child {
        width: 80%;
        min-height: 100px;
        height: auto;
        padding: 0px 10px;
        border: 1px solid black;
        background-color: lightgreen;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <parent-component></parent-component>
      <button @click='handle'>销毁事件</button>
    </div>
    <script>
      //实例化一个事件中心
      const eventHub = new Vue();

      //1.声明父组件
      Vue.component("parent-component", {
        data() {
          return {};
        },
        template: `<div class='parent'>
                     <h3>父组件</h3>
                     <tom-component></tom-component>
                     <hr>
                     <jerry-component></jerry-component>
                    </div>`,
      });

      //2.声明子组件
      Vue.component("tom-component", {
        data() {
          return {};
        },
        template: `<div class='child'>
                    <h3>Tom-Component</h3>
                    <button @click='handle' >逗一下jerry</button>
                   </div>`,
        methods: {
          handle() {
            //通过事件中心,触发自定义的事件
            eventHub.$emit("jerry-event", 2);
          },
        },
      });

      Vue.component("jerry-component", {
        data() {
          return { step: 0 };
        },
        template: `<div class='child'>
                    <h3>Jerry-Component</h3>
                    <h4>{{step}}</h4>
                   </div>`,
        mounted() {
          //mounted生命周期的钩子函数,在jerry-component组件挂载完成之后,执行
          //通过事件中心监听事件
          //console.log('mounted',this);
          // let _this=this;
          eventHub.$on("jerry-event", (val) => {
            console.log("快跑,tom来了...", val, this);
            this.step += val;
          });
        },
      });

      //1. 实例化一个Vue的实例
      let vm = new Vue({
        el: "#app",
        data: {},
        methods:{
          handle(){
            console.log('销毁事件');
            eventHub.$off('jerry-event');
          }
        }
      });
    </script>
  </body>
</html>
